package com.blast.sspai.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;

import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.NetworkImageView;
import com.blast.sspai.R;
import com.blast.sspai.ShareUtil.ShareUtil;
import com.blast.sspai.model.articles.Article;
import com.blast.sspai.model.articles.Banner;
import com.blast.sspai.model.articles.Data;
import com.blast.sspai.util.ClientAPI;
import com.blast.sspai.util.RequestManager;
import com.umeng.socialize.common.SocializeConstants;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.UMSsoHandler;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * author : hg
 * email: 530157892@qq.com
 * 15/6/15.
 */

/**
 * 文章界面
 */
public class ArticleActivity extends AppCompatActivity implements View.OnClickListener {

    TextView txtTitle;
    NetworkImageView imageView;
    WebView webView;
    String css;
    private TextView author;
    private TextView date;
    private Toolbar mToolBar;
    private String title = "标题加载失败";
    private String iconUrl;
    private String url;
    private ShareUtil shareUtil;
    private ContentLoader contentLoader;
    private UMSocialService mController;
    private ByteArrayOutputStream baos;
    private InputStream open;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);

        try {
            open = getAssets().open("css/style_android.css");
            int len;
            byte arr[] = new byte[1024];
            baos = new ByteArrayOutputStream();
            while ((len=open.read(arr))!=-1){
                baos.write(arr,0,len);
            }
            css = new String(baos.toByteArray(),"UTF-8");



        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (baos!=null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (open!=null){
                try {
                    open.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //初始化控件
        initView();

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        Data data = (Data) extras.get("data");
        String aid = extras.getString("id");
        if (data!=null) {
            String id = data.getId();
            contentLoader = new ContentLoader();
            contentLoader.execute(id);

        }else if (aid!=null){
            contentLoader = new ContentLoader();
            contentLoader.execute(aid);
        }

        setSupportActionBar(mToolBar);
        if (mToolBar != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
           // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().isHideOnContentScrollEnabled();
        }
    }

    public void initView() {
        author = (TextView)findViewById(R.id.article_author);
        date = (TextView)findViewById(R.id.article_date);
        txtTitle = (TextView) findViewById(R.id.article_top_title);
        imageView = (NetworkImageView) findViewById(R.id.article_top_image);
        imageView.setDefaultImageResId(R.drawable.pic_ad_default_banner);
        imageView.setErrorImageResId(R.drawable.pic_ad_default_banner);
        webView = (WebView) findViewById(R.id.article_body);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mToolBar = (Toolbar) findViewById(R.id.common_toolbar);
        //初始化分享
        shareUtil = ShareUtil.getShareUtil();
        mController = shareUtil.newInstants(this);
        shareUtil.initSocialSdk();
        SocializeConstants.APPKEY = "558126e767e58ea4e8001818";
    }

    /**
     * 返回按钮的点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private class ContentLoader extends AsyncTask<String, Void, Article> {
        @Override
        protected Article doInBackground(String... params) {
            Article ret = null;
            if (params != null) {
                String id = params[0];
                if (id != null) {
                    ret = ClientAPI.getArticle(id);
                }
            }

            return ret;
        }

        @Override
        protected void onPostExecute(Article article) {
            title = article.getTitle();
            iconUrl = article.getIcon();
            url = article.getUrl();
            String content = article.getContent();
            Banner banner = article.getBanner();
            String imageUrl = banner.getThumbUrl800();
            String authorname = article.getUser().getNickname();
            String created = article.getCreated();
            author.setText(authorname);
            date.setText(created);
            txtTitle.setText(title);

            imageView.setImageUrl(imageUrl, RequestManager.getInstance().getImageLoader());
            //String style = "img{ max-width:90%;height:auto;vertical-align:middle;}";
            //width:100px;height:50px;border:1px solid #000;line-height:50px; margin:0 auto;text-align:center
            String style = "<html><head><style type='text/css' media='all'>"+"img{ max-width:90%;height:auto;}"+css+"</style></head><body>";

            //css = "<html><head><link rel='stylesheet' href='file:///css/style_android.css'/>"+style+"</style></head><body>";
            //webView.loadDataWithBaseURL("about:blank",css+content+"</body></html>","text/html;charset=UTF-8",null,null);
            webView.loadData(style+content+"</body></html>", "text/html;charset=UTF-8", null);
        }
    }

    /**
     * 返回
     * @param view
     */
    public void btnBack(View view){
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        contentLoader.cancel(true);
    }

    /**
     * 创建菜单
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_article, menu);
        return true;
    }

    /**
     * 菜单点击事件
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.toolbar_collection:
                //TODO

                break;
            case R.id.toolbar_share:
                //TODO
                if (title != null && url != null && iconUrl != null) {
                    shareUtil.showCustomUI(iconUrl, url, title);
                } else {
                    Toast.makeText(this, "稍等片刻.", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.toolbar_comments:
                //TODO

                break;
            //TODO 无法监听到事件
            case R.id.home:
                Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}